<?php

class Gallery extends A_Content  {
	
	const content_name = 'Галлерея';
	
	public function __get($param)
	{
		if ($param=='content_name') {
			return self::content_name;
		} else { 
			return false;
		}
	}
	
	/**
	 * Returns instance of SingleGallery class
	 *
	 * @param Integer $id
	 * @return SingleGallery
	 */
	public function getById($id)
	{
		if (!isset($this->_cashe_obj[$id])) {
			$this->_cashe_obj[$id] = new SingleGallery($this->_top,$this,$id);
		}
		
		return $this->_cashe_obj[$id];
	}
	
	
	public function add()
	{
		$this->_top->_sql->exeDummy("INSERT INTO ".TAB_PREF."gallery(add_date,last_mod,json_config) VALUES(NOW(),NOW(),'');");
		$id = $this->_top->_sql->last_insert_id();
		return $this->getById($id);
	}
	
	
}

class SingleGallery extends A_SingleContent  {
	
	private
		$_cashe_obj = array(),		// Здесь кешируется список изображений галереи 
		$_image_types = array(array('main','Главное изображение')); // TODO - временная затычка. позже надо разработать формат настроек xml в таблице gallery и на основании их заполнять этот массив
	
		
		
	/**
	 * Returns the list of images could be linked to every gallery item
	 *
	 * @deprecated in future planed to use json_config field for extra data configuration
	 * @var array
	 */
	public $image_types;
		
	public $config;
	
	public function loader()
	{
		unset($this->image_types);
		unset($this->config);
		
		$get_data = $this->_top->_sql->exe("SELECT * FROM ".TAB_PREF."gallery c WHERE gallery_id={$this->_content_id} ORDER BY `add_date` ASC");
		if (count($get_data)==0)
			throw $this->_top->Utils->PushError('Gallery object not found Id: '.$this->_content_id,'Системная ошибка. Обратитесь к администратору');
		else {
			$this->_data = $get_data[0];
			
			$this->_data['images'] = array();
			$get_images = $this->_top->_sql->exe("SELECT image_id FROM ".TAB_PREF."gallery_image 
				WHERE gallery_id={$this->_content_id} ORDER BY sequence ASC");
			for ($i=0;$i<count($get_images);$i++) {
				array_push($this->_data['images'],$get_images[$i]['image_id']);
			}
			
		}
		return true;
	}
	
	public function __get($param)
	{
		
		if ($param=="images")
			return false;
		elseif ($param=='config') {
			try {
				return $this->_top->Utils->json_decoder($this->json_config);
			} catch (Exception $e) {
				return false;
			}
		} elseif ($param=="image_types") {
			return $this->_image_types;
		} elseif (!isset($this->_data[$param]))
			return false; 
		else 
			return $this->_data[$param];
	}
	
	public function __set($param,$value)
	{
		if ($param=="gallery_id")
			return false;
		elseif ($param=="add_date")
			return false;
		elseif ($param=="images")
			return false;
		else {
			if ($param=="last_mod") {
				$this->xml = $this->xml;
				return true;
			} elseif (!isset($this->_data[$param])) {
				return false;
			}
			
			$this->_data[$param] = $value;
			$ins_value = $this->_top->Utils->prepareValueForSQL($value);
			$this->_top->_sql->exeDummy("UPDATE ".TAB_PREF."gallery SET `$param`='$ins_value',last_mod=NOW() WHERE gallery_id={$this->_content_id}");
			return true;
		}
			
	}
	
	public function add()
	{
		$cfg = $this->config;
		$fields = '';
		$values = '';
		if ($cfg!==false) {
			for ($c=0;$c<count($cfg);$c++) {
				$fields .= ",`{$cfg[$c][1]}`";
				$values .= ",'{$this->_top->Content($cfg[$c][2])->add()->_content_id}'";
			}
		}
		$this->_top->_sql->exeDummy("INSERT INTO ".TAB_PREF."gallery_image(add_date,last_mod,gallery_id$fields) 
			VALUES(NOW(),NOW(),{$this->_content_id}{$values})");
		$image_id = $this->_top->_sql->last_insert_id();
		for ($k=0;$k<count($this->_image_types);$k++) {
			try {
				$cover = $this->_top->Cover->add();
				$cover_id = $cover->_content_id;
				$this->_top->_sql->exeDummy("INSERT INTO ".TAB_PREF."gallery_image2cover(image_id,cover_id,key_name) 
					VALUES($image_id,$cover_id,'{$this->_image_types[$k][0]}');");
			} catch (Exception $e) {
				$cover->delete();
			}
		}
		$this->loader();
		return $this->getById($image_id);
		
	}
	
	/**
	 * Returns instance of GalleryNote class
	 *
	 * @param Integer $id
	 * @return GalleryNote
	 */
	public function getById($id) {
		if (!isset($this->_cashe_obj[$id]))
			$this->_cashe_obj[$id] = new GalleryNote($this->_top,$this,$id);
		return $this->_cashe_obj[$id];
	}
	
	
	public function image($idx)
	{
		if (!isset($this->_data['images'][$idx])) 
			return false;
		else {
			return $this->getById($this->_data['images'][$idx]);
		}
		
		
	}
	
	public function length()
	{
		return count($this->_data['images']);
	}
	
	protected function deleter()
	{
		for ($i=0;$i<$this->length();$i++)
			$this->image($i)->delete(); 
		$this->_top->_sql->exeDummy("DELETE FROM ".TAB_PREF."gallery WHERE gallery_id={$this->_content_id};");
		
	}
	
	public function applyXML($xml_obj) {
		$this->json_config = trim(!is_null($xml_obj) ? $xml_obj[0]->getText() : '');
	}
	
	
	
}

class GalleryNote extends A_SingleContent 
{
	private $_extra_data_map;
	private $_extra_data_fields = array();
	
	public function loader()
	{
		$get_image = $this->_top->_sql->exe("SELECT * FROM ".TAB_PREF."gallery_image WHERE image_id={$this->_content_id}");
		if (count($get_image)==0) {
			return false;
		} else {
			$this->_data = $get_image[0];
			$this->_data['image_list'] = array();
			$get_image_list = $this->_top->_sql->exe("SELECT * FROM ".TAB_PREF."gallery_image2cover WHERE image_id={$this->_content_id}");
			for ($i=0;$i<count($get_image_list);$i++) {
				$this->_data['image_list'][$get_image_list[$i]['key_name']] = $get_image_list[$i]['cover_id'];
			}
			
			
			$cfg = $this->_parent->config;
			for ($c=0;$c<count($cfg);$c++) {
				$this->_extra_data_map[$cfg[$c][0]] = $cfg[$c];
				array_push($this->_extra_data_fields,$cfg[1]);
			}
			
		}
	}
	
	public function __get($param)
	{
		if ($param=="image_list")
			return false;
		elseif (isset($this->_data[$param]))
			return $this->_data[$param];
		elseif (isset($this->_extra_data_map[$param])) {
			try {
				return $this->_top->Content($this->_extra_data_map[$param][2])->getById($this->__get($this->_extra_data_map[$param][1]));
			} catch (Exception $e) {
				$new_obj = $this->_top->Content($this->_extra_data_map[$param][2])->add();
				$this->__set($this->_extra_data_map[$param][1],$new_obj->_content_id);
				return $new_obj; 
			}
		} elseif (isset($this->_data['image_list'][$param])) { 
			return $this->_top->Cover->getById($this->_data['image_list'][$param]);
		} else { 
			return false;
		}
	}
	
	public function __set($param,$value)
	{
		if ($param=="image_list")
			return false;
		elseif ($param=="image_id")
			return false;
		elseif ($param=="add_date")
			return false;
		elseif ($param=="sequence") {
			// TODO - вставить инструмент управления порядком изображений в списке
			return false;
		} elseif (isset($this->_extra_data_map[$param])) {
			return false;
		} elseif (isset($this->_data[$param])) {
			if ($param=="last_mod") {
				$this->name = $this->name;
				return true;
			} elseif (!isset($this->_data[$param])) {
				return false;
			}
			
			$this->_data[$param] = $value;
			$ins_value = $this->_top->Utils->prepareValueForSQL($value);
			$this->_top->_sql->exeDummy("UPDATE ".TAB_PREF."gallery_image SET `$param`='$ins_value',last_mod=NOW() WHERE image_id={$this->_content_id}");
			return true;
		} else 
			return false;
	}
	
	protected function deleter()
	{
		$key_names = array_keys($this->_data['image_list']);
		for ($k=0;$k<count($key_names);$k++) {
			$this->_top->Cover->getById($this->_data['image_list'][$key_names[$k]])->delete();
		}
		
		$cfg = $this->_parent->config;
		if ($cfg!==false) {
			for ($c=0;$c<count($cfg);$c++) {
				$this->_top->Content($cfg[$c][2])->getById($this->__get($cfg[$c][1]))->delete();
			}
		}
		
		$this->_top->_sql->exeDummy("DELETE FROM ".TAB_PREF."gallery_image2cover WHERE image_id={$this->_content_id}");
		$this->_top->_sql->exeDummy("DELETE FROM ".TAB_PREF."gallery_image WHERE image_id={$this->_content_id}");
	
		$this->_parent->loader();
			
	}
	

}

?>